//
//  UITextView+extension.swift
//  XinLangWeibo10
//
//  Created by 白利兵 on 15/11/2.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit

extension UITextView: UITextViewDelegate {
    /// 图片表情完整字符串内容
    var emoticonText: String {
        
        var strM = String()
        
        let attrText = attributedText
        
        // 遍历属性文本
        attrText.enumerateAttributesInRange(NSRange(location: 0, length: attrText.length),
            options: []) { (dict, range, _) -> Void in
                
                // - 如果字典中包含 NSAttachment 说明是图片
                // - 否则是字符串，可以通过 range 获得
                if let attachment = dict["NSAttachment"] as? EmoticonAttachement {
                    strM += attachment.emoticon!.chs ?? ""
                } else {
                    let str = (attrText.string as NSString).substringWithRange(range)
                    
                    strM += str
                }
        }
        
        return strM
    }
    func insertEmoticon(emoticon: Emoticon){
        self.font = UIFont.systemFontOfSize(18)
        // 回退按钮
        if emoticon.isRemove {
            deleteBackward()
            return
        }
        // 空白按钮
        if emoticon.isEmpty {
            return
        }
        // 表情字符串
        if let emo = emoticon.emoji {
            replaceRange(selectedTextRange!, withText: emo)
            return
        }
        // 思路：表情图片以附件（attactment）形式添加到属性文本中
        delegate!.textViewDidChange?(self)
        // 获取表情图片文本
        let imageText = EmoticonAttachement(emoticon: emoticon).imageText(self.font!)
        // 获取图片文本
        // 记录textView的属性文本并将其转化为可变文本
        let attributeM = NSMutableAttributedString(attributedString: attributedText)
        attributeM.addAttribute(NSFontAttributeName, value: font!, range: self.selectedRange)
        // 插入图片文本
        //attributeM.insertAttributedString(imageText, atIndex: selectedRange.location)
        attributeM.replaceCharactersInRange(self.selectedRange, withAttributedString: imageText)
        // 获取光标的位置
        let selectedRange = self.selectedRange
        // 重新给textView属性文本赋值
        attributedText = attributeM
        // 重新定位光标的位置
        self.selectedRange = NSRange.init(location: selectedRange.location + 1, length: 0)
    
    }

}